<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="120">
            <!--            <el-form-item label="平台" prop="platformName">-->
            <!--              <el-select v-model="queryParams.platformId" placeholder="请选择平台" clearable>-->
            <!--                <el-option v-for="item in platform_type" :key="item.value" :label="item.label" :value="item.value" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable />
            </el-form-item>
            <el-form-item label="产品类型" prop="productType">
              <el-select v-model="queryParams.productType" placeholder="请选择产品类型" clearable>
                <el-option v-for="dict in product_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="链接评级" prop="productLevel">
              <el-select v-model="queryParams.productLevel" placeholder="请选择链接评级" clearable>
                <el-option v-for="dict in product_level" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="sku" prop="fnSku">
              <el-input v-model="queryParams.fnSku" placeholder="请输入sku" clearable />
            </el-form-item>
            <el-form-item label="通用码" prop="universalCode">
              <el-input v-model="queryParams.universalCode" placeholder="请输入通用码" clearable />
            </el-form-item>
            <el-form-item label="父产品名称" prop="parentProductName">
              <el-input v-model="queryParams.parentProductName" placeholder="请输入父产品名称" clearable />
            </el-form-item>
            <el-form-item label="数据来源" prop="dataSource">
              <el-select v-model="queryParams.dataSource" placeholder="请选择数据来源" clearable>
                <el-option v-for="dict in data_source" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <div v-if="showMoreQueryConditionFlag" id="moreQueryDiv">
              <el-form-item label="开发负责人" prop="developUserId">
                <user-input v-model="queryParams.developUserId" v-model:name="queryParams.developUserName" placeholder="请选择负责人"></user-input>
              </el-form-item>
              <el-form-item label="设计负责人" prop="designUserId">
                <user-input v-model="queryParams.designUserId" v-model:name="queryParams.designUserName" placeholder="请选择负责人"></user-input>
              </el-form-item>
              <el-form-item label="平面负责人" prop="planeUserId">
                <user-input v-model="queryParams.planeUserId" v-model:name="queryParams.planeUserName" placeholder="请选择负责人"></user-input>
              </el-form-item>
              <el-form-item label="运营负责人" prop="operaUserId">
                <user-input v-model="queryParams.operaUserId" v-model:name="queryParams.operaUserName" placeholder="请选择负责人"></user-input>
              </el-form-item>
              <el-form-item label="采购负责人" prop="purchaseUserId">
                <user-input v-model="queryParams.purchaseUserId" v-model:name="queryParams.purchaseUserName" placeholder="请选择负责人"></user-input>
              </el-form-item>
              <el-form-item label="站外推广负责人" prop="promoUserId">
                <user-input v-model="queryParams.promoUserId" v-model:name="queryParams.promoUserName" placeholder="请选择负责人"></user-input>
              </el-form-item>
            </div>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="d-caret" @click="showMoreQueryConditionFlag = !showMoreQueryConditionFlag"
                >{{ showMoreQueryConditionFlag ? '收起' : '展开' }}更多查询条件
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['oa:product:add']" type="primary" plain icon="Plus" @click="handleAdd">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['oa:product:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['oa:product:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <!--<el-col :span="1.5">
            <el-button v-hasPermi="['oa:product:export']" type="warning" plain icon="Download" @click="handleDownLoadTemplate">导入模板下载</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['oa:product:export']" type="warning" plain icon="Download" @click="handleExport">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['oa:product:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="产品ID" align="center" prop="productId" />
        <!--        <el-table-column label="平台名称" align="center" prop="platformId">-->
        <!--          <template #default="scope">{{ platform_type.find((item) => item.value === scope.row.platformId)?.label }} </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="产品名称" align="center" prop="productName" width="200" />
        <el-table-column label="产品类型" align="center" prop="productType">
          <template #default="scope">{{ product_type.find((item) => item.value === scope.row.productType)?.label }} </template>
        </el-table-column>
        <el-table-column label="父产品" align="center" prop="parentProductName">
          <template #default="scope">
            <span>{{ scope.row.parentProductId ? scope.row.parentProductName : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="通用码" align="center" prop="universalCode" width="150" />
        <el-table-column label="sku" align="center" prop="fnSku" width="150" />
        <el-table-column label="链接评级" align="center" prop="productLevel">
          <template #default="scope">{{ product_level.find((item) => item.value === scope.row.productLevel)?.label }} </template>
        </el-table-column>
        <!--        <el-table-column label="产品售价" align="center" prop="productPrice" />-->
        <!--        <el-table-column label="产品毛重" align="center" prop="grossWeight" />-->
        <!--        <el-table-column label="产品净重" align="center" prop="netWeight" />-->
        <el-table-column label="开发责任人" align="center" prop="developUserName" />
        <el-table-column label="设计责任人" align="center" prop="designUserName" />
        <el-table-column label="平面责任人" align="center" prop="planeUserName" />
        <el-table-column label="运营责任人" align="center" prop="operaUserName" />
        <el-table-column label="采购责任人" align="center" prop="purchaseUserName" />
        <el-table-column label="站外推广责任人" align="center" prop="promoUserName" />
        <el-table-column label="站外推广责任人" align="center" prop="promoUserName" />
        <el-table-column label="关联辅料" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <router-link :to="'/product/product-material-rel/index/' + scope.row.fnSku" class="link-type">
              <span>关联辅料</span>
            </router-link>
          </template>
        </el-table-column>
        <!--        <el-table-column label="包装方式" align="center" prop="packageMethodName" />-->
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['oa:product:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['oa:product:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改产品对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" append-to-body>
      <el-form ref="productFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" />
            </el-form-item>
            <el-form-item label="父产品" prop="parentProductId">
              <product-select
                v-model="form.parentProductId"
                v-model:name="form.parentProductName"
                :product-type="2"
                :disabled="dialog.title === '修改产品'"
                clearable
              />
            </el-form-item>
            <el-form-item label="通用码" prop="universalCode">
              <el-input v-model="form.universalCode" placeholder="请输入通用码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品类型" prop="productType">
              <el-select v-model="form.productType" placeholder="请选择产品类型" clearable :disabled="dialog.title === '修改产品'">
                <el-option v-for="dict in product_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="sku" prop="fnSku">
              <el-input v-model="form.fnSku" :disabled="dialog.title === '修改产品'" placeholder="请输入sku" />
            </el-form-item>
            <el-form-item label="链接评级" prop="productLevel">
              <el-select v-model="form.productLevel" placeholder="请选择链接评级" clearable>
                <el-option v-for="dict in product_level" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-divider />
          <el-col :span="12">
            <el-form-item label="开发负责人" prop="developUserId">
              <user-input v-model="form.developUserId" v-model:name="form.developUserName" placeholder="请选择负责人"></user-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设计负责人" prop="designUserId">
              <user-input v-model="form.designUserId" v-model:name="form.designUserName" placeholder="请选择负责人"></user-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平面负责人" prop="planeUserId">
              <user-input v-model="form.planeUserId" v-model:name="form.planeUserName" placeholder="请选择负责人"></user-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运营负责人" prop="operaUserId">
              <user-input v-model="form.operaUserId" v-model:name="form.operaUserName" placeholder="请选择负责人"></user-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购负责人" prop="purchaseUserId">
              <user-input v-model="form.purchaseUserId" v-model:name="form.purchaseUserName" placeholder="请选择负责人"></user-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站外推广负责人" prop="promoUserId">
              <user-input v-model="form.promoUserId" v-model:name="form.promoUserName" placeholder="请选择负责人"></user-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider />
        <!--组合产品值为0，显示子产品-->
        <!--        <el-form-item v-if="form.productType === '0'" label="子产品" prop="childIds">-->
        <!--          <ChildProductDialog v-model="form.childIds"></ChildProductDialog>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item v-if="form.productType === '0'" label="子产品" prop="childIds">-->
        <!--          <ChildProductSelect v-model="form.childIds" placeholder="子产品" :product-type="1" :multiple="true" />-->
        <!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product" lang="ts">
import UserInput from '@/components/business/UserInput.vue';
// import MaterialSelect from '@/components/business/MaterialInput.vue';
import { pageProduct, getProduct, delProduct, addProduct, updateProduct } from '@/api/product/product';
import { ProductVO, ProductQuery, ProductForm } from '@/api/product/product/types';
import ProductSelect from '@/views/product/product/ProductSelect.vue';
// import ChildProductSelect from '@/views/product/product/ChildProductSelect.vue';
// import ChildProductDialog from '@/views/product/product/ChildProductDialog.vue';
import { list } from '@/api/material/material';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { product_type, data_source, product_level } = toRefs<any>(proxy?.useDict('product_type', 'data_source', 'product_level'));
const productList = ref<ProductVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const productFormRef = ref<ElFormInstance>();
const materialList = ref([]);
const backupList = ref([]);

const showMoreQueryConditionFlag = ref(false);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData = {
  productId: undefined,
  productName: undefined,
  parentProductId: undefined,
  parentProductName: undefined,
  fnSku: undefined,
  universalCode: undefined,
  productType: undefined,
  developUserId: undefined,
  developUserName: undefined,
  designUserId: undefined,
  designUserName: undefined,
  planeUserId: undefined,
  planeUserName: undefined,
  operaUserId: undefined,
  operaUserName: undefined,
  purchaseUserId: undefined,
  promoUserId: undefined,
  remark: undefined,
  productLevel: undefined
};
const data = reactive<PageData<ProductForm, ProductQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: undefined, // 产品名称
    productType: undefined, // 产品类型（普通产品，组合产品）
    fnSku: undefined, // sku
    developUserId: undefined, // 开发责任人用户Id
    developUserName: undefined, // 开发责任人
    designUserId: undefined, // 设计责任人用户Id
    designUserName: undefined, // 设计责任人
    planeUserId: undefined, // 平面责任人用户Id
    planeUserName: undefined, // 平面责任人
    operaUserId: undefined, // 运营责任人用户Id
    operaUserName: undefined, // 运营责任人
    purchaseUserId: undefined, // 采购责任人用户Id
    purchaseUserName: undefined, // 采购责任人
    promoUserId: undefined, // 站外推广责任人用户Id
    promoUserName: undefined, // 站外推广责任人
    universalCode: undefined,
    productLevel: undefined,
    params: {} // 其他参数
  },
  rules: {
    productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
    platformId: [{ required: true, message: '平台不能为空', trigger: 'blur' }],
    productType: [{ required: true, message: '产品类型不能为空', trigger: 'blur' }],
    fnSku: [{ required: true, message: 'sku不能为空', trigger: 'blur' }],
    developUserId: [{ required: true, message: '开发责任人不能为空', trigger: 'blur' }],
    designUserId: [{ required: true, message: '设计责任人不能为空', trigger: 'blur' }],
    planeUserId: [{ required: true, message: '平面责任人不能为空', trigger: 'blur' }],
    operaUserId: [{ required: true, message: '运营责任人不能为空', trigger: 'blur' }],
    purchaseUserId: [{ required: true, message: '采购责任人不能为空', trigger: 'blur' }],
    universalCode: [{ required: true, message: '通用码不能为空', trigger: 'blur' }],
    productLevel: [{ required: true, message: '链接评级不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 平台选择*/
// const { platform_type } = toRefs<any>(proxy?.useDict('platform_type'));

// const filterTask = (query: string) => {
//   if (query) {
//     const a = materialList.value.filter((item) => {
//       return item.materialName.includes(query);
//     });
//     if (a.length > 0) {
//       materialList.value = a;
//     } else {
//       materialList.value = [];
//     }
//   } else {
//     materialList.value = backupList.value;
//   }
// };

/** 查询产品列表 */
const getList = async () => {
  loading.value = true;
  const res = await pageProduct(queryParams.value);
  productList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
//
// const getMaterialList = async () => {
//   loading.value = true;
//   const res = await list({ materialType: '0' });
//   materialList.value = res.data;
//   backupList.value = res.data;
//   loading.value = false;
// };

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  productFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.developUserName = '';
  queryParams.value.designUserName = '';
  queryParams.value.planeUserName = '';
  queryParams.value.operaUserName = '';
  queryParams.value.purchaseUserName = '';
  queryParams.value.promoUserName = '';
  queryParams.value.developUserId = '';
  queryParams.value.designUserId = '';
  queryParams.value.planeUserId = '';
  queryParams.value.operaUserId = '';
  queryParams.value.purchaseUserId = '';
  queryParams.value.promoUserId = '';
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProductVO[]) => {
  ids.value = selection.map((item) => item.productId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加产品';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ProductVO) => {
  loading.value = true;
  reset();
  const _productId = row?.productId || ids.value[0];
  const res = await getProduct(_productId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改产品';
  loading.value = false;
};

/** 提交按钮 */
const submitForm = () => {
  productFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (!form.value.developUserId) {
        proxy?.$modal.msgError('开发责任人不能为空');
        buttonLoading.value = false;
        return;
      }
      if (!form.value.designUserId) {
        proxy?.$modal.msgError('设计责任人不能为空');
        buttonLoading.value = false;
        return;
      }
      if (!form.value.planeUserId) {
        proxy?.$modal.msgError('平面责任人不能为空');
        buttonLoading.value = false;
        return;
      }
      if (!form.value.operaUserId) {
        proxy?.$modal.msgError('运营责任人不能为空');
        buttonLoading.value = false;
        return;
      }
      if (!form.value.purchaseUserId) {
        proxy?.$modal.msgError('采购责任人不能为空');
        buttonLoading.value = false;
        return;
      }

      if (form.value.productId) {
        await updateProduct(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addProduct(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProductVO) => {
  const _productIds = row?.productId || ids.value;
  await proxy?.$modal.confirm('是否确认删除产品编号为"' + _productIds + '"的数据项？').finally(() => (loading.value = false));
  await delProduct(_productIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/product/export',
    {
      ...queryParams.value
    },
    `产品列表_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  // getMaterialList();
});
</script>
